-- UIFateChainUser
-- Create by cheny3 Nov/24/2016
-- 命运的链玩家

-- UIFateChainUser继承自Layer
UIFateChainUser = class("UIFateChainUser", function()
    return cc.Layer:create();
end);

function UIFateChainUser.create(openType, info)
    return UIFateChainUser.new(openType, info);
end

-- 内部变量声明
local REQUEST_WAIT_TIME = 30;      -- 超时等待时间
local HERO_MODEL_SCALE  = 0.667;   -- 模型缩放比例

-- 构造函数
function UIFateChainUser:ctor(openType, info)
    -- 初始化
    self:setName("UIFateChainUser");

    local node = cc.CSLoader:createNode("layout/fate_chain/RequestInfo.csb");
    self:addChild(node);
    self.node = node;
    self.openType = openType;
    self.info = info;

    if self.openType == "answer" then
        self.leftTime = REQUEST_WAIT_TIME;
    end

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化
    self:init();

    -- 重绘
    self:redraw();

    self:tickRedraw()

    -- 适配
    self:resize();
end

-- 适配
function UIFateChainUser:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化
function UIFateChainUser:init()

end

-- 重绘
function UIFateChainUser:redraw()
    -- 目标宠物/昵称
    local petId = self.info["activity_pet"];
    local nickname = self.info["name"];
    if self.openType == "answer" then
        -- 接收方，显示对方的
        petId = self.info["request_pet"];
        nickname = self.info["nickname"];
    end

    -- 标题
    local title1 = findChildByName(self.node, "CT/title");
    title1:setVisible(true);
    title1:setString(PetM.query(petId, "name"));
    TextStyleM.setTitleStyle(title1);

    -- 副标题
    local title2 = findChildByName(self.node, "CT/subtitle");
    title2:setVisible(true);
    title2:setString(getNickName(nickname));
    --TextStyleM.setSubheadStyle(title2);
    -- 系统字
    title2:setFontSize(TextStyleM.TEXT_SIZE_MIDDLE);
    title2:setTextColor(TextStyleM.TEXT_COLOR_DARK_BROWN);
    --TextStyleM.setOutlineStyle(title2, nil, nil ,true);
    title2:setPositionY(title2:getPositionY() - 10);
    TextStyleM.setShadowStyle(title2, cc.size(-0.1, -0.1));

    -- 气泡部分
    self:redrawBubble();

    -- 重绘按钮
    self:redrawButton();

    -- 绘制说明部分
    self:redrawDesc();

    -- 气泡呼吸
    local tipNode = findChildByName(self.node, "CT/tip");
    playBubbleAnima(tipNode, false, 0.8);

    -- 创建模型
    self:createHeroModel();
end

-- 创建英雄模型
function UIFateChainUser:createHeroModel()
    local headImg = findChildByName(self.node, "CT/head_image");
    local modelNode = findChildByName(self.node, "CT/model_node");

    -- 获取当前出战英雄
    local heroId = self.info["activity_pet"];
    if self.openType == "answer" then
        -- 接收方，显示对方的
        heroId = self.info["request_pet"];
    end

    local modelId = PetM.query(heroId, "default_model");
    if tonumber(self.info["activity_costume"]) > 0 then
        -- 时装
        modelId = EquipM.query(self.info["activity_costume"], "dbase")["pet_model_id"];
    end

    local largetIcon = PetM.queryModel(modelId, "large_icon");
    local iconPath = getHeroLargeIconPath(largetIcon);

    createHeroModel(modelId, headImg, modelNode, HERO_MODEL_SCALE, iconPath);
end

-- 每秒回调
function UIFateChainUser:tickRedraw()
    if self.tick then
        return;
    end

    local function callback()
        self:redrawButton();

        if self.openType == "wait" then
            self:redrawBubble(true);
        else
            self:redrawBubble();
        end

        if self.openType == "wait" and tonumber(self.leftTime) < 0 then
            -- 取消
            FateChainM.cancelRequest();
            self.openType = "request";
            self:redrawButton();
            self:redrawBubble();
        elseif self.openType == "answer" and tonumber(self.leftTime) < 0 then
            -- 拒绝
            self:answerFateChain(0);
        end
        performWithDelay(self, callback, 1);
    end

    self.tick = true;
    callback();
end

-- 重绘气泡部分
function UIFateChainUser:redrawBubble(effect)
    if effect and tonumber(self.leftTime) % 3 ~= 0 then
        return;
    end

    local imageNode = findChildByName(self.node, "CT/tip/image");
    if self.openType ~= "wait" then
        -- 国籍
        imageNode:setScale(1.2);
        local nationId = tonumber(self.info["nation_id"]);
        local icon = TopM.queryNationality(nationId, "icon");
        imageNode:loadTexture(getNationalityIconPath(icon));
    else
        -- 倒计时
        imageNode:setScale(0.9);
        imageNode:loadTexture(getLevelItemIconPath("sandglass"));
        if effect then
            local rotate = cc.RotateBy:create(1.0, 360);
            imageNode:runAction(rotate);
        end
    end
end

-- 重绘按钮
function UIFateChainUser:redrawButton()
    local oneNode = findChildByName(self.node, "CT/button_one");
    local twoNode = findChildByName(self.node, "CT/button_two");
    local btnOne = findChildByName(self.node, "CT/button_one/btn_ok");
    local btnOk = findChildByName(self.node, "CT/button_two/btn_ok");
    local btnCancel = findChildByName(self.node, "CT/button_two/btn_cancel");
    local btnBack = findChildByName(self.node, "BT/btn_back");

    if self.openType == "request" then
        -- 请求
        oneNode:setVisible(true);
        twoNode:setVisible(false);

        btnOne:setTitleText(getLocStr("btn_text_fate_request"));

        -- TODO 先不置灰了
        if false and ME.user.dbase:query("fate_link", 0) <= 0 then
            -- 置灰
            btnOne:setTouchEnabled(false);
            btnOne:setBright(false);
        else
            btnOne:setTouchEnabled(true);
            btnOne:setBright(true);
        end
        btnBack:setTitleText(getLocStr("btn_text_back"));
    elseif self.openType == "wait" then
        -- 等待
        oneNode:setVisible(true);
        twoNode:setVisible(false);

        btnOne:setTitleText(string.format(getLocStr("btn_text_wait_answer"), self.leftTime));
        self.leftTime = self.leftTime - 1;

        -- 置灰
        btnOne:setTouchEnabled(false);
        btnOne:setBright(false);
        btnBack:setTitleText(getLocStr("btn_text_cancel"));
    elseif self.openType == "answer" then
        -- 回答
        oneNode:setVisible(false);
        twoNode:setVisible(true);

        btnOk:setTitleText(string.format(getLocStr("btn_text_agree"), self.leftTime));
        btnCancel:setTitleText(getLocStr("btn_text_refuse"));
        self.leftTime = self.leftTime - 1;

        -- TODO 先不置灰了
        if false and ME.user.dbase:query("fate_link", 0) <= 0 then
            -- 置灰
            btnOk:setTouchEnabled(false);
            btnOk:setBright(false);
        else
            btnOk:setTouchEnabled(true);
            btnOk:setBright(true);
        end
    end
end

-- 绘制说明部分
function UIFateChainUser:redrawDesc()
    local descLabel = findChildByName(self.node, "CT/desc");
    self.descLabel = self.descLabel or descLabel;
    TextStyleM.setTextStyle(self.descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN);

    local desc = "";
    if self.openType == "request" or self.openType == "wait" then
        desc = string.format(getLocStr("fate_request_desc"),
            self.info["pet_nums"], FateChainM.getRelationship(self.info["rid"]));
    elseif self.openType == "answer" then
        desc = string.format(getLocStr("fate_answer_desc"), FateChainM.getRelationship(self.info["request_rid"]));
    end

    self.descLabel = applyString(self.descLabel, desc);
end

-- 注册事件处理回调函数
function UIFateChainUser:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UIFateChainUser", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIFateChainUser" then
        elseif para["lose"] == "UIFateChainUser" then
        end
    end);

    -- 关注服务器状态更新事件
    EventMgr.register("UIFateChainUser", event.SERVER_STATUS_UPDATE, function(para)
        local data = para.data;
        if data["fate_chain_open"] ~= 1 then
            -- 命运之链禁止
            UIMgr.getCurrentScene():removeFormByName("UIFateChainUser");
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIFateChainUser 界面析构清理");
            EventMgr.removeAll("UIFateChainUser");
        elseif eventType == "enter" then

        end
    end);
end

-- 请求链接
function UIFateChainUser:requestFateChain()
    if ME.user.dbase:query("fate_link", 0) <= 0 then
        -- 体力不足
        alert(getLocStr("lack_fate_link"));
        return;
    end

    FateChainM.requestFateChain(self.info["rid"]);

    self.leftTime = REQUEST_WAIT_TIME;

    -- 变成等待状态
    self.openType = "wait";

    self:redrawButton();
    self:redrawBubble();
end

-- 回答链接
function UIFateChainUser:answerFateChain(result)
    if result == 1 and ME.user.dbase:query("fate_link", 0) <= 0 then
        -- 体力不足
        alert(getLocStr("lack_fate_link"));
        return;
    end

    FateChainM.answerFateChain(result);
    -- 关闭自身界面
    UIMgr.getCurrentScene():removeFormByName("UIFateChainUser");
end

-- 注册点击事件
function UIFateChainUser:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if self.openType == "wait" then
                -- 取消
                FateChainM.cancelRequest();
            elseif self.openType == "answer" then
                -- 拒绝
                self:answerFateChain(0);
            end
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIFateChainUser");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
    if self.openType == "answer" then
        btnBack:setVisible(false);
    end

    -- 单个按钮
    local btnOne = findChildByName(self.node, "CT/button_one/btn_ok");
    local function onBtnOneClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if self.openType ~= "request" then
                return;
            end

            self:requestFateChain();
        end
    end
    btnOne:addTouchEventListener(onBtnOneClick);
    TextStyleM.setTextStyle(btnOne, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

    -- 双按钮/确认
    local btnOk = findChildByName(self.node, "CT/button_two/btn_ok");
    local function onBtnOkclick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if self.openType ~= "answer" then
                return;
            end

            self:answerFateChain(1);
        end
    end
    btnOk:addTouchEventListener(onBtnOkclick);
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, getLocKerning() - 2);

    -- 双按钮/取消
    local btnCancel = findChildByName(self.node, "CT/button_two/btn_cancel");
    local function onBtnCancelclick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if self.openType ~= "answer" then
                return;
            end

            self:answerFateChain(0);
        end
    end
    btnCancel:addTouchEventListener(onBtnCancelclick);
    TextStyleM.setTextStyle(btnCancel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
end